package com.wangsiyu.zookeeper.rmi.server;

import com.wangsiyu.zookeeper.rmi.common.Constant;
import com.wangsiyu.zookeeper.rmi.common.HelloService;
import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.concurrent.CountDownLatch;

public class ServiceProvider {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceProvider.class);
    //用于等待SyncConnected事件触发后继续执行当前线程
    private CountDownLatch latch = new CountDownLatch(1);
    //发布RMI服务并注册RMI地址到ZooKeeper中
    public void publish(Remote remote, String host, int port) {
        String url = publishService(remote, host, port);//发布RMI服务并返回RMI地址
        if(url !=null){
            ZooKeeper zk = connectServer();//连接ZooKeeper服务器并获取ZooKeeper对象
            if (zk !=null){
                createNode(zk, url);//创建ZNode 并将RMI地址放入ZNode上
            }
        }
    }

    private void createNode(ZooKeeper zk, String url) {
        try {
            //将url地址从字符串转换为字节数组
            byte[] data = url.getBytes();
            String path = zk.create(Constant.ZK_PROVIDER_PATH, data, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL_SEQUENTIAL);//创建一个临时顺序节点ZNode
            LOGGER.debug("create zookeeper node ({} => {})", path, url);
        } catch (KeeperException | InterruptedException e) {
            LOGGER.error("", e);
        }
    }

    private ZooKeeper connectServer() {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(Constant.ZK_CONNECT_STRING, Constant.ZK_SESSION_TIME, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
                        latch.countDown();
                    }
                }
            });
            latch.await();
        } catch (IOException | InterruptedException e) {
            LOGGER.error("", e);
        }
        return zk;
    }

    private String publishService(Remote remote, String host, int port) {
        String url = null;
        try {
            url = String.format("rmi://%s:%d/%s", host, port, remote.getClass().getName());
            LocateRegistry.createRegistry(port);
            Naming.rebind(url, remote);
            LOGGER.debug("server publish rmi service (url:{})", url);
        } catch (RemoteException | MalformedURLException e) {
            LOGGER.error("",e);
        }
        return url;
    }
}
